<?php


namespace app\admin\system\controller;


use app\admin\system\service\AdminService;
use app\admin\system\validate\AdminLoginValidate;
use app\model\SysAdmin;
use support\exception\BadException;
use support\utils\LockUtil;
use support\utils\RandomUtil;

class LoginController extends BaseController
{
    protected $noNeedLogin = [
        'login',
        'test',
    ];

    public function login()
    {
        AdminLoginValidate::goCheck(input());

        $username = input('username');
        $password = input('password');
        $user = SysAdmin::where([
            'username' => $username
        ])->field(['id', 'password', 'salt', 'status'])->find();
        if (!$user) {
            throw new BadException("账号密码错误");
        }
        if ($user['status'] != 0) {
            throw new BadException("账号已经被禁用");
        }
        if (!AdminService::checkPassword($password, $user['password'], $user['salt'])) {
            throw new BadException("账号密码错误");
        }

        $token = md5($username . $password . RandomUtil::randomStr());
        $user->token = $token;
        $user->ip = request()->getRealIp();
        $user->save();
        return $this->success([
            "tokenName" => "Authorization",
            'tokenValue' => $token
        ]);
    }

    public function loginOut()
    {
        SysAdmin::where([
            'uid' => request()->uid
        ])->update([
            'token' => ""
        ]);
        return $this->success();
    }

    public function test()
    {
        echo time() . PHP_EOL;
        LockUtil::lockWithRetry("test", function () {
            echo "111" . PHP_EOL;
        });
        LockUtil::lockWithRetry("test", function () {
            echo "222" . PHP_EOL;
        });
        LockUtil::lockWithRetry("test", function () {
            echo "333" . PHP_EOL;
        });
        echo time() . PHP_EOL;
        return 1;
    }
}